package com.csaba.db.actions;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

import com.csaba.db.ui.OpenDatabaseDialog;
import com.csaba.util.LoggerHelper;

/**
 * Our sample action implements workbench action delegate.
 * The action proxy will be created by the workbench and
 * shown in the UI. When the user tries to use the action,
 * this delegate will be created and execution will be 
 * delegated to it.
 * @see IWorkbenchWindowActionDelegate
 */
public class OpenUserAction implements IWorkbenchWindowActionDelegate
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();
	private IWorkbenchWindow window;
	private String selected;

	/**
	 * The constructor.
	 */
	public OpenUserAction()
	{
	}

	/**
	 * The constructor with preselected project
	 */
	public OpenUserAction( final String selected )
	{
		this.selected = selected;
	}

	/**
	 * The action has been activated. The argument of the
	 * method represents the 'real' action sitting
	 * in the workbench UI.
	 * @see IWorkbenchWindowActionDelegate#run
	 */
	public void run( final IAction action )
	{
		final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		try
		{
			root.clearHistory(null);
			root.refreshLocal(IResource.DEPTH_INFINITE, null);
			if ( root.getProjects().length < 1 )
			{
				MessageDialog.openWarning(window.getShell(), "Felhasználói fiók megnyitása",
						"Jelenleg nincs elérhető adatbázis.\nHasználja az \"új felhasználó\" menüpontot!");
			}
			else
			{
				final OpenDatabaseDialog dialog = new OpenDatabaseDialog(window.getShell(), selected);
				dialog.open();
			}
		}
		catch ( final Exception ex )
		{
			MessageDialog.openError(window.getShell(), "Error", "Exception occured: " + ex.getMessage());
			logger.log(Level.SEVERE, "Error craeting new database.", ex);
		}

	}

	/**
	 * Selection in the workbench has been changed. We 
	 * can change the state of the 'real' action here
	 * if we want, but this can only happen after 
	 * the delegate has been created.
	 * @see IWorkbenchWindowActionDelegate#selectionChanged
	 */
	public void selectionChanged( final IAction action, final ISelection selection )
	{
	}

	/**
	 * We can use this method to dispose of any system
	 * resources we previously allocated.
	 * @see IWorkbenchWindowActionDelegate#dispose
	 */
	public void dispose()
	{
	}

	/**
	 * We will cache window object in order to
	 * be able to provide parent shell for the message dialog.
	 * @see IWorkbenchWindowActionDelegate#init
	 */
	public void init( final IWorkbenchWindow window )
	{
		this.window = window;
	}
}